﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Nizm0.QOT.Library.Forms
{
    public partial class SqlConnectionProblem : Form
    {
        private Objects.Server _server;
        public SqlConnection con;

        public SqlConnectionProblem(string comment, Objects.Server server)
        {
            InitializeComponent();
            label_Server.Text = server.Address;
            textBox_Login.Text = server.Login;
            label_Comment.Text = comment;
            comboBox_SSPI.SelectedIndex = server.SSPI ? 0 : 1;
            _server = server;
        }

        private void bt_OK_Click(object sender, EventArgs e)
        {

            con = comboBox_SSPI.SelectedIndex == 0 ? new SqlConnection(_server.GetConnectionString(true, 1)) : new SqlConnection(_server.GetConnectionString(1, textBox_Login.Text, maskedTextBox.Text));

            try
            {
                con.Open();

                _server.Login = textBox_Login.Text.Trim();
                _server.Password = maskedTextBox.Text;
                _server.SSPI = comboBox_SSPI.SelectedIndex == 0 ? true : false;
                this.Close();
            }
            catch (SqlException ex)
            {
                switch (ex.Number)
                {
                    case 53:
                        {
#if DEBUG
                            MessageBox.Show("Server not found", "Wharning");
#endif
                            break;
                        }
                    case 18452:
                        {
#if DEBUG
                            MessageBox.Show("Login: " + textBox_Login.Text + " nod exist", "Wharning");
#endif
                            label_Comment.Text = "Login: " + textBox_Login.Text + " nod exist";
                            break;
                        }
                    case 18456:
                        {
#if DEBUG
                            MessageBox.Show("Login faild for user: " + textBox_Login.Text, "Wharning");
#endif
                            label_Comment.Text = "Login faild for user: " + textBox_Login.Text;
                            break;
                        }
                }
            }
            finally
            {
            }
        }

        private void comboBox_SSPI_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox_SSPI.SelectedIndex == 0)
            {
                panel_Login.Enabled = false;
            }
            else
                panel_Login.Enabled = true;
        }

        private void bt_Cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
